/**
 * gMapProvider module
 */

 function gMapProvider($element){
     this.$element = $element;
     this.iframe = this.getIframe();
     this.iframe.appendTo(this.$element);
     this.iframe.on('load',
         function() {
             this.gmapPicker = this.iframe[0].contentWindow.gmapPicker;
             this.geocode = this.iframe[0].contentWindow.geocode;
             this.gMapDistrictSearch = this.iframe[0].contentWindow.gMapDistrictSearch;
             this.gmap = this.iframe[0].contentWindow.gmap;
             this.initGeocode();
             this.gMapDistrictSearch('country', '中国', this.$scope.initProvince);
             this.gMapDistrictSearch('province', this.$scope.form.model.province, this.$scope.initCity);
         }.bind(this));
 };
 gMapProvider.prototype = {
     getIframe: function() {
         return $('<iframe>').attr({
             src: is.CONST.urls.gmap,
             width: '180',
             height: '150',
             frameborder: 0,
             allowtransparency: 1
         });
     },
     initGeocode: function() {
         if (this.$scope.form.model.lat && this.$scope.form.model.lng) {
             this.geocodeByLatLng(function(lat, lng) {
                 if (this.$scope.form.model.lat != lat || this.$scope.form.model.lng != lng) {
                     this.$scope.form.name.$setDirty();
                 };
                 this.$scope.form.model.lat = lat;
                 this.$scope.form.model.lng = lng;
                 this.$scope.$$phase || this.$scope.$apply();
             }.bind(this));
         }
     },
     getAddress: function () {
         var selectorProvince = document.getElementById('province');
         var selectorCity = document.getElementById('city');
         var address = '';

         if (selectorProvince && '-省-' != selectorProvince.value) {
             address += selectorProvince.value;
         }

         //直辖市的城市名称会影响定位 其他有规律的影响定位因素也可以排除一下
         var municipalities = ['重庆市市辖区', '北京市市辖区', '天津市市辖区', '上海市市辖区', '-城市-'];
         if (selectorCity && -1 == municipalities.indexOf(selectorCity.value)) {
             address += selectorCity.value;
         }
         address += this.$scope.form.model.target || '';
         return address;
     },
     geocodeByTarget: function(callback) {
         var address = this.getAddress();
         var options = {
             address: address,
             geocode_back: callback
         }
         this.geocode(options);
     },
     geocodeByLatLng: function(callback) {
         var options = {
             address: this.$scope.form.model.target,
             lat: this.$scope.form.model.lat,
             lng: this.$scope.form.model.lng,

             geocode_back: callback
         };
         this.geocode(options);
     }
 };

 module.exports = gMapProvider;
